import { Reducer } from 'redux';
import { Effect } from 'dva';
import { router } from 'umi';
import {
  fetchAccountLoginAsync,
  fetchVerfiyCodeAsync,
  updatePasswordAsync,
  IUserInfo,
} from '@/services/login';
import { setAuthToken } from '@/utils/request';
import { getPageQuery } from '@/utils/utils';
import { stringify } from 'querystring';
import { message } from 'antd';

export interface LoginModelState {
  currentAuthority?: 'user' | 'guest' | 'admin';
  userInfo?: IUserInfo;
}

export interface LoginModelType {
  namespace: string;
  state: LoginModelState;
  effects: {
    login: Effect;
    logout: Effect;
    getVerifyCode: Effect;
    updatePassword: Effect;
  };
  reducers: {
    setUserInfo: Reducer<LoginModelState>;
  };
}

const PolicyModel: LoginModelType = {
  namespace: 'login',
  state: {
    userInfo: {},
  },
  effects: {
    *login({ payload }, { call, put }) {
      const res = yield call(fetchAccountLoginAsync, payload);

      if ('0' === res.code) {
        const { menus = [] } = res.data;

        yield put({
          type: 'setUserInfo',
          payload: res.data,
        });

        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params as { redirect: string };
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = menus[0].url;
            return;
          }
        }
        router.replace(redirect || menus[0].url);
      }
    },
    *logout({ payload }, { call, put }) {
      const { redirect } = getPageQuery();

      if (window.location.pathname !== '/user/login' && !redirect) {
        router.replace({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        });
      }
    },
    *getVerifyCode({ payload }, { call, put }) {
      const res = yield call(fetchVerfiyCodeAsync, payload);

      if ('0' === res.code) {
        return res;
      }
    },
    *updatePassword({ payload }, { call, put }) {
      const res = yield call(updatePasswordAsync, payload);

      if ('0' === res.code) {
        message.success('密码更新成功');
        return res;
      }
    },
  },
  reducers: {
    setUserInfo(state, { payload }) {
      const { token } = payload;
      setAuthToken(token); // 设置请求体
      localStorage.setItem('userInfo', JSON.stringify(payload)); // 设置缓存

      return {
        ...state,
        userInfo: payload,
      };
    },
  },
};

export default PolicyModel;
